package io.renren.util;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.concurrent.TimeUnit;

import org.slf4j.LoggerFactory;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * <p>
 * </p>
 *
 * @author yuxiaobin
 * @date 2017/8/21
 */
public class SendSMSByWebUtils {

    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger("SendSMSByWebUtils");

    private static final String SEND_URL = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    private static final String USER_NAME = "yourname";
    private static final String PASSWORD = "yourpassword";

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    //TODO:
    private static final String MSG_TEMPLATE_EN = "Your sms code is {0}";
    private static final String MSG_TEMPLATE_CN = "短信验证码为{0}";

    public static boolean sendVerifyCodeMsgByTemplate(String phoneNum, String verifyCode, String locale) {
        if ("EN".equalsIgnoreCase(locale)) {
            return sendSMSByWS(phoneNum, MessageFormat.format(MSG_TEMPLATE_EN, verifyCode));
        } else {
            return sendSMSByWS(phoneNum, MessageFormat.format(MSG_TEMPLATE_CN, verifyCode));
        }
    }

    //client.getParams().setContentCharset("UTF-8");
    //method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
    public static boolean sendSMSByWS(String phoneNum, String content) {
        RequestBody requestBody = new FormBody.Builder().add("account", USER_NAME)
                .add("password", MD5Utils.MD5Encode(PASSWORD))
                .add("mobile", phoneNum)
                .add("content", content)
                .build();
        Request request = new Request.Builder()
                .addHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8")
                .url(SEND_URL)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            String respStr = response.body().string();
            System.out.println("SendSMSByWebUtils.sendSMSByWS(): response Str = " + respStr);//TODO
            logger.info("SendSMSByWebUtils.sendSMSByWS(): response Str = "+respStr);
            return true;
        } catch (IOException e) {
            e.printStackTrace();//TODO:
            logger.error("sendSMSByWS() error", e);
            return false;
        } finally {
            if(response!=null){
                response.close();
            }
        }
    }
}
